<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-25
 * Time: 下午9:09
 */

namespace home\models;


use common\components\tools\ArrayHelper;
use common\components\tools\Html;
use common\config\Env;
use common\models\db\User;
use yii\base\Model;

class FormLogin extends Model
{
    public $name;
    public $password;
    public $remember = 1;
    public $code;
    public $back_url;

    public function attributeLabels()
    {
        return [
            'name' => "用户名",
            'password' => "密码",
            'remember' => "保存30天",
            'code' => "验证码",
        ];
    }

    public function rules()
    {
        return [
            [['name', 'password'], 'trim'],
            [['name', 'password', 'code'], 'required'],
            ['remember', 'boolean'],
            ['code', 'captcha'],
            ['name', 'ruleCheckName'],
            ['password', 'validatePassword'],
            ['back_url', 'string'],
        ];
    }

    public function ruleCheckName($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUserByName();
            if (!$user) {
                $this->addError($attribute, '用户不存在');
            }
            if ($user && $user->username == Env::$yii2app_console_login_name){
                $err_msg = "用户不存在";
                $this->addError($attribute, $err_msg);
            }
            if ($user && $user->status != User::STATUS_ACTIVE){
                $err_msg = User::getStatus()[$user->status];
                $this->addError($attribute, $err_msg);
            }
        }
    }

    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUserByName();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '用户名或密码错误');
            }
        }
    }

    public function login()
    {
        if ($this->validate()) {
            $user = $this->getUserByName();
            return \Yii::$app->user->login($user, $this->remember ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * @param $name
     * @return array|User|null|\yii\db\ActiveRecord
     */
    public function getUserByName()
    {
        $user = User::find()
            ->where(['username' => $this->name])
            ->one();
        return $user;
    }

    public static function getLoginBoxA($text = '登陆', $url = ['#'], $options = [])
    {
        $str = '';
        if (\Yii::$app->user->isGuest){
            $o = ArrayHelper::merge($options, [
                'data-toggle' => 'modal',
                'data-target' => '#login-box',
            ]);
            $str = Html::a($text, $url, $o);
        }
        return $str;
    }
}